<template>
    <div class="division_manage_view">
        <!-- 查询 -->
        <div class="division_manage_view_box division_manage_header">
            <div class="custom-title">分账方信息</div>
            <div class="custom-main">
                <el-row :gutter="24">
                    <el-col class="custom-form-col" :span="8"> <span>商户名称：</span>{{ baseInfo?.name }} </el-col>
                    <el-col class="custom-form-col" :span="8">
                        <span>主体类型：</span>{{ baseInfo?.split_account_type_name }}
                    </el-col>
                    <el-col class="custom-form-col" :span="8">
                        <span>统一社会信用代码：</span>{{ baseInfo?.credit_no }}
                    </el-col>
                    <el-col class="custom-form-col" :span="8">
                        <span>分账方式：</span>{{ baseInfo?.split_type_name }}
                    </el-col>
                </el-row>
            </div>
        </div>
        <div class="division_manage_view_box division_manage_view_bottom">
            <div class="custom-title">分账接收方信息</div>
            <div class="custom-main">
                <!-- 按钮 -->
                <div class="btn-group">
                    <!-- 开通账户 -->
                    <div class="btn-group-left">
                        共<span>{{ totalCount }}</span
                        >条数据
                    </div>
                    <div class="btn-group-right">
                        <span>注：同一个分账方最多添加20个分账接收方。</span>
                        <SelectAccount
                            name="添加分账接收方"
                            title="选择分账接收方"
                            :divisionType="baseInfo?.split_type"
                            :selectedDivisionNum="tableList.length"
                            :splitOpenNo="baseInfo?.open_no"
                            :moduleType="2"
                            :splitOpenId="route.query.id"
                            @handle-close="handleClose"></SelectAccount>
                    </div>
                </div>
                <!-- 列表 -->
                <!-- :height="tableHeight - 48" -->
                <el-table
                    ref="tableRef"
                    :data="tableList"
                    row-key="id"
                    :class="{ 'el-table-empty': !tableList?.length }">
                    <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                        <template v-if="prop === 'name'" #header>
                            <span class="p-l-5">分账接收方信息</span>
                        </template>
                        <template #default="{ row }">
                            <template v-if="prop === 'name'">
                                <div class="corp-name">
                                    <div class="corp-name-main">
                                        <ZwTooltip :content="row.name" :line="2" />
                                    </div>
                                    <div class="corp-name-sub" v-if="row.credit_no">
                                        <ZwTooltip :content="row.credit_no" />
                                    </div>
                                </div>
                            </template>
                            <template v-if="prop === 'ratio'">
                                <span>{{ getRadio(row.ratio) }}</span>
                            </template>
                            <template v-if="prop === 'operations'">
                                <span
                                    v-for="{ label, fn, ref } in row.operations"
                                    :key="label"
                                    @click="fn(row, ref)"
                                    size="small"
                                    class="table-button button--small">
                                    {{ label }}
                                </span>
                            </template>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <div class="table-empty">
                            <img
                                src="https://img.static-keyid.cn/toolspace/scrm/2023/10/1697683499137ngcb4fpdwjr9ijb4.png" />
                            <div>暂无数据</div>
                        </div>
                    </template>
                </el-table>
            </div>
        </div>
        <!-- <div class="division_manage_view_footer">
            <el-button type="primary" @click="handleGoBack">返回列表</el-button>
        </div> -->
        <AcceptInfo
            v-model="showInfo"
            :tableData="acceptArr"
            type="edit"
            :splitOpenId="route.query.id"
            @handle-confirm="handleClose"></AcceptInfo>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, h, nextTick } from 'vue';
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
import request from '@/request/index';
import { setLayout, resetLayout, resizeTableHeight, getTableHeight, resizeTableRemove } from '@/hooks/layout';
import { confirmHandler } from '@/commons/utils';
import AcceptInfo from '../../components/AcceptInfo.vue';
import SelectAccount from '../../components/SelectAccount/SelectAccount.vue';
import ZwTooltip from '@/components/ZwTooltip.vue';

/* ----------------------------添加分账方-start---------------------------- */
const handleClose = value => {
    value && queryListHandler();
};
/* ----------------------------添加分账方-end---------------------------- */

const route = useRoute(); // 路由
const router = useRouter();

const baseInfo = reactive({}); // 查询表单
const tableRef = ref(null);
const totalCount = ref(0); // 数据总数
let tableList = reactive([]); // 表格数据
const showInfo = ref();

// 格式化比例
const getRadio = val => (baseInfo.split_type === 'API' || ['--', null, undefined, ''].includes(val) ? '--' : val + '%');

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '分账接收方信息', prop: 'name', minWidth: '300' },
        { label: '主体类型', prop: 'split_account_type_name', minWidth: '150' },
        { label: '分账比例', prop: 'ratio', minWidth: '150' },
        { label: '操作', prop: 'operations', width: '160', fixed: 'right' }
    ];
    return baseTableColumns;
});

/**
 * 分页查询
 */

// let loading = ref(false);
const queryListHandler = async notScroll => {
    // loading.value = true;
    const res = await request('splitAccountManageView', { id: route.query.id });
    // loading.value = false;
    const { data } = res || {};
    Object.assign(baseInfo, data.split_account_info);
    const list = (data?.split_account_receiver_info || [])?.map(item => {
        // 根据不同状态显示不同按钮
        const btns = {
            0: { label: '修改分账比例', fn: editHandler, ref: 'authRef' },
            1: { label: '删除', fn: removeHandler, ref: 'removeRef' }
        };

        item.operations = [];
        if (baseInfo.split_type === 'API') {
            // API下只展示删除
            item.operations = [btns[1]];
        } else {
            item.operations = [btns[0], btns[1]];
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = tableList.length;
    nextTick(() => {
        // 加载数据后将table滚动条滚动到table最顶部和最左边
        !notScroll && tableRef?.value?.scrollTo(0, 0);
    });
};

/**
 * 删除
 */
const removeHandler = row => {
    // 删除接口
    confirmHandler({
        params: [
            'splitAccountManageDeleteReceiver',
            { split_account_id: route.query.id, split_account_receiver_id: row.id }
        ],
        title: `确定要删除分账接收方【${row.name}】吗？ `,
        subTitle: '删除后，该商户将不再接收分账方的分账。',
        callback: queryListHandler,
        successMsg: '删除成功'
    });
};

const acceptArr = ref([]);
// 设置分账比例
const editHandler = row => {
    const obj = Object.assign({}, row, {
        corp_name: row.name,
        corp_unified_social_credit_code: row.credit_no,
        corp_main_type_name: row.split_account_type_name
    });
    acceptArr.value = [obj] || [];
    showInfo.value = true;
};

const getAllData = () => {
    queryListHandler();
};

// 返回上一页
const handleGoBack = () => {
    router.go(-1);
};

let tableHeight = ref(300);
onMounted(() => {
    setLayout('division-manage-view-layout');
    getAllData();
    // setTimeout(() => {
    //     resizeTableHeight('division_manage_view_bottom', tableHeight, 'bottom-page');
    // }, 0);
});
onBeforeUnmount(() => {
    resetLayout('division-manage-view-layout');
    // resizeTableRemove();
});

onBeforeRouteLeave((to, from, next) => {
    next();
});
</script>
<style lang="scss">
.division-manage-view-layout {
    height: 100%;
    padding: 0 !important;
    background-color: #f3f3f3 !important;
}
.not-border td.el-table__cell {
    border-bottom: 0;
}
.p-l-5 {
    padding-left: 5px;
}
</style>
<style lang="scss" scoped>
@import './scss/index.scss';
</style>
